package main

import (
	"database/sql"
	"fmt"
	"github.com/mozillazg/go-pinyin"
	"log"
	"strings"

	_ "github.com/go-sql-driver/mysql"
)

func main() {
	updateHanZiPy()
}

func updateHanZiPy() {
	// 请根据实际情况修改数据库连接信息
	db, err := sql.Open("mysql", "root:root@tcp(39.108.131.252:3308)/haoxuedb")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// 测试数据库连接
	err = db.Ping()
	if err != nil {
		log.Fatal(err)
	}

	qSql := `select chinese_character from t_chinese_dictionary where chinese_pinyin_seq is null`
	rows, err := db.Query(qSql)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()
	for rows.Next() {
		var character string
		err = rows.Scan(&character)
		if err == nil {
			py := getFullPinyin(character)
			pySeq := getPinyin(character)
			uSql := fmt.Sprintf(`UPDATE t_chinese_dictionary SET chinese_pinyin='%s', chinese_pinyin_seq='%s' WHERE chinese_character='%s';`, py, pySeq, character)
			_, _ = db.Exec(uSql)
		}
	}
}

func getFullPinyin(hans string) string {
	a := pinyin.NewArgs()
	a.Style = pinyin.Tone // 带声调的风格
	a.Heteronym = true    // 启用多音字模式
	pinyinSlice := pinyin.Pinyin(hans, a)
	for _, item := range pinyinSlice {
		join := strings.Join(item, ",")
		return join
	}
	return ""
}

func getPinyin(hans string) string {
	a := pinyin.NewArgs()
	a.Style = pinyin.Tone3
	a.Heteronym = true // 启用多音字模式
	pinyinSlice := pinyin.Pinyin(hans, a)
	for _, item := range pinyinSlice {
		join := strings.Join(item, ",")
		return join
	}
	return ""
}
